package com.xhwl.logistics.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.enums.vehicle.CardStatusEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.logistics.dao.VehcCarDao;
import com.xhwl.logistics.dao.VehcCardCarDao;
import com.xhwl.logistics.dao.VehcCardDao;
import com.xhwl.common.enums.vehicle.CardTypeEnum;
import com.xhwl.logistics.enums.VehicleCodeEnum;
import com.xhwl.common.pojo.cent.vehicle.VehcCar;
import com.xhwl.common.pojo.cent.vehicle.VehcCard;
import com.xhwl.common.pojo.cent.vehicle.VehcCardCar;
import com.xhwl.common.query.cent.vehicle.CardQuery;
import com.xhwl.logistics.service.cent.IAccountService;
import com.xhwl.logistics.service.cent.IProjectService;
import com.xhwl.logistics.service.IVehcCardService;
import com.xhwl.logistics.util.MakeCardNum;
import com.xhwl.common.vo.cent.vehicle.CardPageVO;
import com.xhwl.common.vo.cent.vehicle.CardVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lu.Aaron
 * @since 2021-02-08
 */
//@Service
public class VehcCardServiceImpl extends ServiceImpl<VehcCardDao, VehcCard> implements IVehcCardService {
    @Autowired
    private VehcCarDao vehcCarDao;
    @Autowired
    private VehcCardDao vehcCardDao;
    @Autowired
    private VehcCardCarDao vehcCardCarDao;
    @Autowired
    private IAccountService iAccountService;
    @Autowired
    private IProjectService iProjectService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson add(CardVO cardVO, Account account) {
        //TODO 根据String syncManufacturer = passageVO.getSyncManufacturer()判断选择供应商，同步数据;
        //TODO 若syncManufacturer空，通过项目查询供应商，在进行同步数据
        if (cardVO.getIsRegistered()==0) {
            //未登记
            //1.先新增车辆
            VehcCar vehcCar = new VehcCar();
            BeanUtils.copyProperties(cardVO,vehcCar,"id","isHoldAccount","type");
            vehcCar.setRegisterAccountId(account.getId());
            vehcCar.setType(cardVO.getCarType());
            vehcCar.setRegisterTime(new Date());
            Integer count = vehcCarDao.selectCount(new QueryWrapper<VehcCar>().eq("plate_number", cardVO.getPlateNumber()));
            if (count>=1) {
                throw new BusinessException(VehicleCodeEnum.PLATE_NUMBER_EXISTED.description);
            }

            vehcCarDao.insert(vehcCar);
            //2.绑定车卡
            VehcCard vehcCard = new VehcCard();
            BeanUtils.copyProperties(cardVO,vehcCard,"id");
            //设置唯一编号number
            String number = MakeCardNum.makeCardNum();
            vehcCard.setType(cardVO.getCardType());
            vehcCard.setNumber(number);
            vehcCardDao.insert(vehcCard);
            VehcCardCar vehcCardCar = new VehcCardCar();
            vehcCardCar.setCarId(vehcCar.getId());
            vehcCardCar.setCardId(vehcCard.getId());
            vehcCardCarDao.insert(vehcCardCar);
        }else if(cardVO.getIsRegistered()==1){
            //已登记
            VehcCar vehcCar = vehcCarDao.selectOne(new QueryWrapper<VehcCar>().eq("plate_number", cardVO.getPlateNumber()));
            Integer count = vehcCardCarDao.selectCount(new QueryWrapper<VehcCardCar>().eq("car_id", vehcCar.getId()));
            if (count>0) {
                throw new BusinessException("该车已绑定车卡，请勿继续绑定");
            }
            //1.绑定车卡
            VehcCard vehcCard = new VehcCard();
            BeanUtils.copyProperties(cardVO,vehcCard,"id");
            //设置唯一编号number
            vehcCard.setType(cardVO.getCardType());
            String number = MakeCardNum.makeCardNum();
            vehcCard.setNumber(number);
            vehcCardDao.insert(vehcCard);
            VehcCardCar vehcCardCar = new VehcCardCar();
            vehcCardCar.setCarId(vehcCar.getId());
            vehcCardCar.setCardId(vehcCard.getId());
            vehcCardCarDao.insert(vehcCardCar);
        }
        return ResultJson.success("新增成功");
    }

    @Override
    public ResultJson edit(CardVO cardVO) {
        //TODO 根据String syncManufacturer = passageVO.getSyncManufacturer()判断选择供应商，同步数据;
        //TODO 若syncManufacturer空，通过项目查询供应商，在进行同步数据
        if (cardVO.getCardType().equals(CardTypeEnum.FREE)) {
            //免费卡只修改有效时间
            VehcCard vehcCard = vehcCardDao.selectById(cardVO.getId());
            vehcCard.setEffectiveTime(cardVO.getEffectiveTime());
            vehcCard.setExpirationTime(cardVO.getExpirationTime());
            vehcCardDao.updateById(vehcCard);

        }
        return ResultJson.success("修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson delete(Integer id) {
        //删除卡，以及卡和车的绑定关系
        vehcCardDao.deleteById(id);
        vehcCardCarDao.delete(new QueryWrapper<VehcCardCar>().eq("card_id",id));
        return ResultJson.success("删除成功");
    }

    @Override
    public ResultJson cardPage(CardQuery carQuery) {
        CardTypeEnum type = carQuery.getType();
        Integer current = carQuery.getCurrent();
        if (null==type) {
            throw new BusinessException(VehicleCodeEnum.CARD_TYPE_LACK.description);
        }
        List<Integer> projectIdsQuery = carQuery.getProjectIds();
        if (null==projectIdsQuery||projectIdsQuery.isEmpty()) {
            throw new BusinessException(VehicleCodeEnum.PROJECT_ID_LACK.description);
        }
        if (null!=carQuery.getOwnerAccountIds()&&carQuery.getOwnerAccountIds().isEmpty()) {
            //为空则是有经过手机号或车主姓名过滤的没有此人的结果，则返回空
            Page<CardPageVO> page = new Page<>();
            page.setTotal(0);
            page.setCurrent(carQuery.getCurrent());
            page.setSize(carQuery.getPageSize());
            return ResultJson.success(page);
        }
        carQuery.setCurrent((carQuery.getCurrent() - 1) * carQuery.getPageSize());
        List<CardPageVO> cardPageVOS = vehcCardDao.queryCardList(carQuery);
        List<Integer> projectIds = cardPageVOS.stream().map(v -> v.getProjectId()).collect(Collectors.toList());
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.withIdList(projectIds);
        List<Project> projects = iProjectService.list(projectQuery, null);
        Date now = new Date();
        cardPageVOS.forEach(cpv->{
            projects.forEach(p->{
                if (cpv.getProjectId().equals(p.getId())) {
                    cpv.setProjectName(p.getName());
                }
            });
            if (cpv.getCardType().equals(CardTypeEnum.FREE)) {
                cpv.setApplicableArea("全部");
                cpv.setApplicableParking("全部");
                cpv.setApplicablePassage("全部");
            }
            if (cpv.getEffectiveTime().after(now)) {
                cpv.setStatus(CardStatusEnum.INVALID);
            }else if (cpv.getExpirationTime().before(now)){
                cpv.setStatus(CardStatusEnum.EXPIRED);
            }else if (now.after(cpv.getEffectiveTime())&&now.before(cpv.getExpirationTime())){
                cpv.setStatus(CardStatusEnum.VALID);
            }
        });
        Long total = vehcCardDao.queryCardTotal(carQuery);
        Page<CardPageVO> page = new Page<>();
        page.setTotal(total);
        page.setCurrent(current);
        page.setSize(carQuery.getPageSize());
        page.setRecords(cardPageVOS);
        return ResultJson.success(page);
    }
}
